package com.hzeport.bgs22emduty.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
//import com.hzeport.bgs22emduty.dto.MessageSendDTO;
import com.hzeport.bgs22emduty.dto.ScreenDutyNoticeListDTO;
import com.hzeport.bgs22emduty.dto.ScreenDutyNoticeListDTO;
import com.hzeport.bgs22emduty.dto.ScreenDutyNoticeListSaveDTO;
import com.hzeport.bgs22emduty.dto.SmsPersonDTO;
import com.hzeport.bgs22emduty.entity.*;
//import com.hzeport.bgs22emduty.feign.MessageSendFeign;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
//import com.hzeport.bgs22emduty.feign.MessageSendFeign;
import com.hzeport.bgs22emduty.outbound.*;
import com.hzeport.bgs22emduty.service.SecurityLogService;
import com.hzeport.bgs22emduty.util.MessageSendUtil;
import com.hzeport.bgs22emduty.vo.ScreenDutyNoticeList.ScreenDutyNoticeListVO;
import com.hzeport.bgs22emduty.vo.ls.ScreenDutyMessageSaveVO;
import com.hzeport.bgs22emduty.vo.ls.ScreenDutyNoticeListLSAnnoSaveVO;
import com.hzeport.bgs22emduty.vo.ls.ScreenDutyNoticeSaveVO;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.hzeport.bgs22emduty.common.utils.IpUtils;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import com.hzeport.bgs22emduty.outbound.db.ScreenDutyNoticeListRepositoryImpl;
import com.hzeport.bgs22emduty.service.ScreenDutyNoticeListService;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * ${comments}
 *
 * @author code generator
 * @date 2023-02-14 09:39:44
 */
@Service
@Slf4j
public class ScreenDutyNoticeListServiceImpl extends BaseServiceImpl<ScreenDutyNoticeListRepositoryImpl, ScreenDutyNoticeList> implements ScreenDutyNoticeListService {

    @Resource
    private ScreenDutyNoticeListRepository screenDutyNoticeListRepository;

    @Resource
    private LoginCompoentService loginCompoentService;

    @Resource
    private BasePersonInfoRepository basePersonInfoRepository;
    @Resource
    private MessageSendUtil messageSendUtil;
    @Resource
    private ScreenDutyNoticeListCustomRepository screenDutyNoticeListCustomRepository;
    @Resource
    private BaseDeptInfoRepository baseDeptInfoRepository;
    @Resource
    private ScreenMapsRepository screenMapsRepository;
    @Resource
    private SecurityLogService securityLogService;
//    @Resource
//    private MessageSendFeign messageSendFeign;

    @Override
    public Object page(ScreenDutyNoticeListDTO dto) {
//        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        LambdaQueryWrapper<ScreenDutyNoticeList> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(StringUtils.isNotBlank(userInfoDetailVO.getCustomscode()),ScreenDutyNoticeList::getCustomId,userInfoDetailVO.getCustomscode());
        queryWrapper.like(StringUtils.isNotBlank(dto.getKeyWord()),ScreenDutyNoticeList::getTitle,dto.getKeyWord());
        if (!CollectionUtils.isEmpty(dto.getList()) && StringUtils.isNotBlank(dto.getList().get(0))){
            LocalDateTime startLocalDateTime = LocalDate.parse(dto.getList().get(0), DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay();
            queryWrapper.ge(ScreenDutyNoticeList::getCreateTime,startLocalDateTime);
        }
        if (!CollectionUtils.isEmpty(dto.getList()) && StringUtils.isNotBlank(dto.getList().get(1))){
            LocalDateTime endLocalDateTime = LocalDate.parse(dto.getList().get(1), DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay().plusDays(1);
            queryWrapper.le(ScreenDutyNoticeList::getCreateTime,endLocalDateTime);
        }
        queryWrapper.orderByDesc(ScreenDutyNoticeList::getCreateTime);
        Page<ScreenDutyNoticeList> page = screenDutyNoticeListRepository.page(new Page<>(dto.getPageNum(), dto.getPageSize()), queryWrapper);
        List<ScreenDutyNoticeListVO> smsSendPerson = page.getRecords().stream().map(screenDutyNoticeList -> {
            ScreenDutyNoticeListVO screenDutyNoticeListVO = new ScreenDutyNoticeListVO();
            BeanUtil.copyProperties(screenDutyNoticeList, screenDutyNoticeListVO, "smsSendPerson");
            if (StringUtils.isNotBlank(screenDutyNoticeList.getSmsSendPerson())) {
                try{
                    Gson gson = new Gson();
                    List<SmsPersonDTO> smsSendPersons = gson.fromJson(screenDutyNoticeList.getSmsSendPerson(), new TypeToken<List<SmsPersonDTO>>() {
                    }.getType());
                    screenDutyNoticeListVO.setSmsSendPerson(smsSendPersons);
                    screenDutyNoticeListVO.setSmsSendName(smsSendPersons.stream().map(SmsPersonDTO::getName).collect(Collectors.toList()));
                }catch (Exception e){
                    log.info("smsSendPerson转换json异常"+e);
                }
            }
            if (!Objects.isNull(screenDutyNoticeList.getStartTime()) && !Objects.isNull(screenDutyNoticeList.getEndTime())) {
                screenDutyNoticeListVO.setStartAndEndTime(screenDutyNoticeList.getStartTime().toLocalDate()+"至"+screenDutyNoticeList.getEndTime().toLocalDate());
            }
            return screenDutyNoticeListVO;
        }).collect(Collectors.toList());
        Page<ScreenDutyNoticeListVO> screenDutyNoticeListVOPage = new Page<>();
        BeanUtil.copyProperties(page,screenDutyNoticeListVOPage,"records");
        screenDutyNoticeListVOPage.setRecords(smsSendPerson);
        return screenDutyNoticeListVOPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(ScreenDutyNoticeListSaveDTO dto) throws Exception {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        ScreenDutyNoticeList screenDutyNoticeList = new ScreenDutyNoticeList();
        BeanUtil.copyProperties(dto,screenDutyNoticeList,"smsSendPerson");
        if (!CollectionUtils.isEmpty(dto.getSmsSendPerson())) {
            screenDutyNoticeList.setSmsSendPerson(new Gson().toJson(dto.getSmsSendPerson()));
        }
        screenDutyNoticeList.setCreatePerson(userInfoDetailVO.getUserName());
        //发布状态以及需要发送短信条件下
        if ("1".equals(screenDutyNoticeList.getStatus()) && "0".equals(screenDutyNoticeList.getIsMsg())) {
            if (CollectionUtils.isEmpty(dto.getSmsSendPerson())) {
                throw new Exception("发布状态以及需要发送短信条件下,短信接受人不能为空");
            }
            List<String> phones = basePersonInfoRepository.listByIds(dto.getSmsSendPerson().stream().map(SmsPersonDTO::getId).collect(Collectors.toList())).stream().map(BasePersonInfo::getPhone).collect(Collectors.toList());
            for (String phone:phones) {
                messageSendUtil.sendMessage(phone, dto.getMainBody());
            }
        }
        screenDutyNoticeListRepository.save(screenDutyNoticeList);

//        List<ScreenMaps> screenMaps = screenMapsRepository.listByIds(dto.getCustomId());
//        screenMaps=screenMaps.stream().map(i -> {
//            i.setStateFlag(dto.getNoticeType());
//            i.setWarnCont(dto.getMainBody());
//            if("0".equals(dto.getNoticeType()) || "1".equals(dto.getNoticeType())){
//                i.setWarn("1");
//            }else {
//                i.setWarn("0");
//            }
//            i.setStartTime(dto.getStartTime());
//            i.setEndTime(dto.getEndTime());
//            return i;
//        }).collect(Collectors.toList());
//        screenMapsRepository.updateBatchById(screenMaps);

        screenDutyNoticeListCustomRepository.remove(new LambdaQueryWrapper<ScreenDutyNoticeListCustom>()
        .eq(ScreenDutyNoticeListCustom::getNoticeId,screenDutyNoticeList.getId()));
        if (!CollectionUtils.isEmpty(dto.getCustomId())){
            List<ScreenDutyNoticeListCustom> screenDutyNoticeLists=dto.getCustomId().stream().map(i->{
                ScreenDutyNoticeListCustom screenDutyNoticeListCustom=new ScreenDutyNoticeListCustom();
                screenDutyNoticeListCustom.setId(UUID.randomUUID().toString());
                screenDutyNoticeListCustom.setCustomId(i);
                BaseDeptInfo baseDeptInfo=baseDeptInfoRepository.getById(i);
                screenDutyNoticeListCustom.setCustomName(baseDeptInfo.getDeptName());
                screenDutyNoticeListCustom.setNoticeId(screenDutyNoticeList.getId());
                screenDutyNoticeListCustom.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                return screenDutyNoticeListCustom;
            }).collect(Collectors.toList());
            screenDutyNoticeListCustomRepository.saveBatch(screenDutyNoticeLists);
        }
        screenDutyNoticeList.setCustomId(null);
        return true;
    }

    @Override
    public ScreenDutyNoticeListVO detailById(String id) {
        ScreenDutyNoticeList byId = screenDutyNoticeListRepository.getById(id);
        ScreenDutyNoticeListVO screenDutyNoticeListVO = new ScreenDutyNoticeListVO();
        BeanUtil.copyProperties(byId,screenDutyNoticeListVO,"smsSendPerson");
        if (!StringUtils.isBlank(byId.getSmsSendPerson())) {
            try{
                List<SmsPersonDTO> smsSendPersons = new Gson().fromJson(byId.getSmsSendPerson(), new TypeToken<List<SmsPersonDTO>>() {
                }.getType());
                screenDutyNoticeListVO.setSmsSendPerson(smsSendPersons);
                screenDutyNoticeListVO.setSmsSendName(smsSendPersons.stream().map(SmsPersonDTO::getName).collect(Collectors.toList()));
            }catch (Exception e){
                log.info("smsSendPerson转换json异常"+e);
            }
        }
        List<ScreenDutyNoticeListCustom> screenDutyNoticeListCustom=screenDutyNoticeListCustomRepository.list(new LambdaQueryWrapper<ScreenDutyNoticeListCustom>()
                .eq(ScreenDutyNoticeListCustom::getNoticeId,id));
        if (!CollectionUtils.isEmpty(screenDutyNoticeListCustom)){
            screenDutyNoticeListVO.setCustomId(screenDutyNoticeListCustom.stream().map(ScreenDutyNoticeListCustom::getCustomId).collect(Collectors.toList()));
        }
         return screenDutyNoticeListVO;
    }

    @Override
    public BaseResult savelsnote(ScreenDutyNoticeSaveVO screenNoticeSaveVO, HttpServletRequest request) {
        ScreenDutyNoticeList screenDutyNoticeList = new ScreenDutyNoticeList();
        BeanUtils.copyProperties(screenNoticeSaveVO,screenDutyNoticeList);
        if(StringUtils.isEmpty(screenNoticeSaveVO.getId())){
            screenDutyNoticeList.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            screenDutyNoticeList.setCreateTime(LocalDateTime.now());
            screenDutyNoticeList.setUpdateTime(LocalDateTime.now());
            screenDutyNoticeListRepository.save(screenDutyNoticeList);
        }else {
            ScreenDutyNoticeList byId = screenDutyNoticeListRepository.getById(screenNoticeSaveVO.getId());
            if (byId != null){
                screenDutyNoticeList.setRecVersion(byId.getRecVersion());
            }
            screenDutyNoticeList.setUpdateTime(LocalDateTime.now());
            screenDutyNoticeList.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            screenDutyNoticeListRepository.updateById(screenDutyNoticeList);
        }
        SecurityLog operateLog = new SecurityLog();
        operateLog.setCreateBy(screenNoticeSaveVO.getCreatePerson());
        operateLog.setCreateTime(LocalDateTime.now());
        operateLog.setIpAddress( IpUtils.getIpAddr(request));
        operateLog.setSDescription( JSON.toJSONString( screenNoticeSaveVO ) );
        operateLog.setSModule("ZBTXLS");
        operateLog.setSTitle("ZBBC");
        securityLogService.save(operateLog);
        return BaseResult.ok(screenDutyNoticeList,"保存成功");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(ScreenDutyNoticeListSaveDTO dto) {
        ScreenDutyNoticeList screenDutyNoticeList = new ScreenDutyNoticeList();
        BeanUtil.copyProperties(dto,screenDutyNoticeList,"smsSendPerson");
        if (!CollectionUtils.isEmpty(dto.getSmsSendPerson())) {
            screenDutyNoticeList.setSmsSendPerson(new Gson().toJson(dto.getSmsSendPerson()));
        }
        screenDutyNoticeListCustomRepository.remove(new LambdaQueryWrapper<ScreenDutyNoticeListCustom>()
                .eq(ScreenDutyNoticeListCustom::getNoticeId,screenDutyNoticeList.getId()));
        if (!CollectionUtils.isEmpty(dto.getCustomId())){
            List<ScreenDutyNoticeListCustom> screenDutyNoticeLists=dto.getCustomId().stream().map(i->{
                ScreenDutyNoticeListCustom screenDutyNoticeListCustom=new ScreenDutyNoticeListCustom();
                screenDutyNoticeListCustom.setId(UUID.randomUUID().toString());
                screenDutyNoticeListCustom.setCustomId(i);
                BaseDeptInfo baseDeptInfo=baseDeptInfoRepository.getById(i);
                screenDutyNoticeListCustom.setCustomName(baseDeptInfo.getDeptName());
                screenDutyNoticeListCustom.setNoticeId(screenDutyNoticeList.getId());
                screenDutyNoticeListCustom.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
                return screenDutyNoticeListCustom;
            }).collect(Collectors.toList());
            screenDutyNoticeListCustomRepository.saveBatch(screenDutyNoticeLists);
        }
        screenDutyNoticeList.setCustomId(null);
        if (StringUtils.isNotBlank(screenDutyNoticeList.getId())){
            ScreenDutyNoticeList byId = screenDutyNoticeListRepository.getById(screenDutyNoticeList.getId());
            if (byId != null){
                screenDutyNoticeList.setRecVersion(byId.getRecVersion());
            }
        }
        return screenDutyNoticeListRepository.updateById(screenDutyNoticeList);
    }

    @Override
    public BaseResult savelsabno(ScreenDutyNoticeListLSAnnoSaveVO screenDutyNoticeListLSAnnoSaveVO, HttpServletRequest request) {
        ScreenDutyNoticeList screenDutyNoticeList = new ScreenDutyNoticeList();
        if(StringUtils.isEmpty(screenDutyNoticeListLSAnnoSaveVO.getId())){
            screenDutyNoticeList.setTitle(screenDutyNoticeListLSAnnoSaveVO.getTitle());
            screenDutyNoticeList.setMainBody(screenDutyNoticeListLSAnnoSaveVO.getMainBody());
            screenDutyNoticeList.setCreatePerson(screenDutyNoticeListLSAnnoSaveVO.getCreatePerson());
            screenDutyNoticeList.setCustomId(screenDutyNoticeListLSAnnoSaveVO.getCustomId());
            screenDutyNoticeList.setIsMsg(screenDutyNoticeListLSAnnoSaveVO.getIsMsg());
            screenDutyNoticeList.setNoticeType(screenDutyNoticeListLSAnnoSaveVO.getNoticeType());
            screenDutyNoticeList.setStartTime(!StringUtils.isEmpty(screenDutyNoticeListLSAnnoSaveVO.getStartTime())?LocalDateTime.parse(screenDutyNoticeListLSAnnoSaveVO.getStartTime()):null);
            screenDutyNoticeList.setEndTime(!StringUtils.isEmpty(screenDutyNoticeListLSAnnoSaveVO.getEndTime())?LocalDateTime.parse(screenDutyNoticeListLSAnnoSaveVO.getEndTime()):null);
            screenDutyNoticeList.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            screenDutyNoticeList.setCreateTime(LocalDateTime.now());
            screenDutyNoticeList.setUpdateTime(LocalDateTime.now());
            screenDutyNoticeListRepository.save(screenDutyNoticeList);
        }else {
            ScreenDutyNoticeList byId
                    = screenDutyNoticeListRepository.getById(screenDutyNoticeListLSAnnoSaveVO.getId());
            if (byId != null){
                screenDutyNoticeList.setRecVersion(byId.getRecVersion());
            }
            screenDutyNoticeList.setTitle(screenDutyNoticeListLSAnnoSaveVO.getTitle());
            screenDutyNoticeList.setMainBody(screenDutyNoticeListLSAnnoSaveVO.getMainBody());
            screenDutyNoticeList.setCreatePerson(screenDutyNoticeListLSAnnoSaveVO.getCreatePerson());
            screenDutyNoticeList.setCustomId(screenDutyNoticeListLSAnnoSaveVO.getCustomId());
            screenDutyNoticeList.setIsMsg(screenDutyNoticeListLSAnnoSaveVO.getIsMsg());
            screenDutyNoticeList.setNoticeType(screenDutyNoticeListLSAnnoSaveVO.getNoticeType());
            screenDutyNoticeList.setStartTime(!StringUtils.isEmpty(screenDutyNoticeListLSAnnoSaveVO.getStartTime())?LocalDateTime.parse(screenDutyNoticeListLSAnnoSaveVO.getStartTime()):null);
            screenDutyNoticeList.setEndTime(!StringUtils.isEmpty(screenDutyNoticeListLSAnnoSaveVO.getEndTime())?LocalDateTime.parse(screenDutyNoticeListLSAnnoSaveVO.getEndTime()):null);
            screenDutyNoticeList.setUpdateTime(LocalDateTime.now());
            screenDutyNoticeList.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            screenDutyNoticeListRepository.updateById(screenDutyNoticeList);
        }

        ScreenMaps screenMaps = screenMapsRepository.getById(screenDutyNoticeListLSAnnoSaveVO.getCustomId());
        screenMaps.setStateFlag(screenDutyNoticeListLSAnnoSaveVO.getNoticeType());
        screenMaps.setWarnCont(screenDutyNoticeListLSAnnoSaveVO.getMainBody());
        if("0".equals(screenDutyNoticeListLSAnnoSaveVO.getNoticeType()) || "1".equals(screenDutyNoticeListLSAnnoSaveVO.getNoticeType())){
            screenMaps.setWarn("1");
        }else {
            screenMaps.setWarn("0");
        }
        screenMaps.setStartTime(!StringUtils.isEmpty(screenDutyNoticeListLSAnnoSaveVO.getStartTime())?LocalDateTime.parse(screenDutyNoticeListLSAnnoSaveVO.getStartTime()):null);
        screenMaps.setEndTime(!StringUtils.isEmpty(screenDutyNoticeListLSAnnoSaveVO.getEndTime())?LocalDateTime.parse(screenDutyNoticeListLSAnnoSaveVO.getEndTime()):null);
        screenMapsRepository.updateById(screenMaps);
        SecurityLog operateLog = new SecurityLog();
        operateLog.setCreateBy(screenDutyNoticeListLSAnnoSaveVO.getCreatePerson());
        operateLog.setCreateTime(LocalDateTime.now());
        operateLog.setIpAddress( IpUtils.getIpAddr(request));
        operateLog.setSDescription( JSON.toJSONString( screenDutyNoticeListLSAnnoSaveVO ) );
        operateLog.setSModule("YCTXLS");
        operateLog.setSTitle("YCBX");
        securityLogService.save(operateLog);
        return BaseResult.ok(screenDutyNoticeList,"保存成功");
    }
}
